package org.laokouyun.demo.discovery;

import io.grpc.ChannelCredentials;
import io.grpc.netty.NettyChannelBuilder;
import org.springframework.grpc.client.ClientInterceptorsConfigurer;
import org.springframework.grpc.client.GrpcChannelBuilderCustomizer;
import org.springframework.grpc.client.NettyGrpcChannelFactory;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DiscoveryGrpcChannelFactory extends NettyGrpcChannelFactory {


    /**
     * Construct a channel factory instance.
     *
     * @param globalCustomizers      the global customizers to apply to all created channels
     * @param interceptorsConfigurer configures the client interceptors on the created
     *                               channels
     */
    public DiscoveryGrpcChannelFactory(List<GrpcChannelBuilderCustomizer<NettyChannelBuilder>> globalCustomizers, ClientInterceptorsConfigurer interceptorsConfigurer) {
        super(globalCustomizers, interceptorsConfigurer);
        setVirtualTargets((p) -> p.substring(12));
    }

    @Override
    public boolean supports(String target) {
        return target.startsWith("discovery:");
    }

    @Override
    protected NettyChannelBuilder newChannelBuilder(String target, ChannelCredentials credentials) {
        return NettyChannelBuilder.forTarget(String.format("discovery://%s", target), credentials);
    }
}
